<template>
  <div class="home">
    <Header
        @show-profile="showProfile = true"
        @go-home="resetHome"
    />

    <div class="container">
      <div class="main-layout">
        <Sidebar @category-selected="handleCategorySelected" />
        <div class="content-area">
          <!-- 轮播图和热销产品只在没有选择分类时显示 -->
          <template v-if="!selectedCategory && !selectedSubCategory">
            <!-- 轮播图 -->
            <div class="carousel-container card">
              <div class="carousel">
                <div
                    v-for="(slide, index) in slides"
                    :key="index"
                    class="slide"
                    :class="{ 'active': currentSlide === index }"
                >
                  <img :src="slide.image" :alt="slide.title" />
                  <div class="slide-content">
                    <h3 class="slide-title">{{ slide.title }}</h3>
                    <p class="slide-description">{{ slide.description }}</p>
                  </div>
                </div>
                <button class="carousel-control prev" @click="prevSlide">
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <polyline points="15,18 9,12 15,6"/>
                  </svg>
                </button>
                <button class="carousel-control next" @click="nextSlide">
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <polyline points="9,18 15,12 9,6"/>
                  </svg>
                </button>
              </div>
              <div class="carousel-indicators">
                <span
                    v-for="(slide, index) in slides"
                    :key="index"
                    :class="{ 'active': currentSlide === index }"
                    @click="goToSlide(index)"
                ></span>
              </div>
            </div>

            <!-- 热销产品 -->
            <section class="hot-products">
              <div class="section-header">
                <h2 class="section-title">热销产品</h2>
                <p class="section-subtitle">精选优质商品，值得信赖</p>
              </div>
              <div class="product-grid">
                <div
                    v-for="product in hotProducts"
                    :key="product.productId"
                    class="product-card card"
                    @click="goToProductDetail(product.productId)"
                >
                  <div class="product-image">
                    <img :src="getProductImage(product)" :alt="product.productName" />
                    <span class="hot-badge badge badge-error">热销</span>
                  </div>
                  <div class="product-info">
                    <h3 class="product-name">{{ product.productName }}</h3>
                    <div class="price-section">
                      <span class="current-price">¥{{ product.sellingPrice }}</span>
                      <span v-if="product.originalPrice" class="original-price">¥{{ product.originalPrice }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </section>
          </template>

          <ProductList
              :selectedCategoryId="selectedSubCategory || selectedCategory"
              @update:showProfile="showProfile = $event"
          />

          <!-- 商品详情组件 -->
          <ProductDetail
              v-if="selectedProduct"
              :product="selectedProduct"
              @close="selectedProduct = null"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import Header from '@/components/Header.vue';
import Sidebar from '@/components/Sidebar.vue';
import ProductList from '@/components/views/ProductList.vue';
import ProductDetail from './ProductDetail.vue';
import request from '../../utils/request';

const selectedCategory = ref(''); // 一级分类id
const selectedSubCategory = ref(''); // 二级分类id
const showProfile = ref(false);
const currentSlide = ref(0);
const slides = ref([
  {
    image: require('@/assets/banner1.jpg'),
    title: '优质工程机械',
    description: '专业品质，值得信赖'
  },
  {
    image: require('@/assets/banner2.jpg'),
    title: '限时特惠',
    description: '全场8折起'
  }
]);
const hotProducts = ref([]);
const selectedProduct = ref(null);
const carouselInterval = ref(null);

const router = useRouter();

const handleCategorySelected = (categoryId) => {
  if (!categoryId) {
    // 平台首页
    selectedCategory.value = '';
    selectedSubCategory.value = '';
  } else {
    // 判断是一级还是二级分类
    // 由于Sidebar已处理展开逻辑，这里只需记住最后点击的分类id
    // 假设二级分类id都不是一级分类id
    // 这里简单处理：如果当前一级分类下有children且children中有该id，则为二级分类
    // 但前端只传id，直接赋值即可
    // 这里采用：如果当前selectedCategory有值且再次点击，则为二级分类
    if (selectedCategory.value && selectedCategory.value !== categoryId) {
      selectedSubCategory.value = categoryId;
    } else {
      selectedCategory.value = categoryId;
      selectedSubCategory.value = '';
    }
  }
  showProfile.value = false;
};

const resetHome = () => {
  selectedCategory.value = '';
  selectedSubCategory.value = '';
  showProfile.value = false;
};

const prevSlide = () => {
  currentSlide.value = (currentSlide.value - 1 + slides.value.length) % slides.value.length;
};

const nextSlide = () => {
  currentSlide.value = (currentSlide.value + 1) % slides.value.length;
};

const goToSlide = (index) => {
  currentSlide.value = index;
};

const goToProductDetail = (productId) => {
  router.push({
    name: 'ProductDetail',
    params: { id: productId }
  });
};

const getProductImage = (product) => {
  return product.productImg || product.product_image || require('@/assets/product-default.png');
};

const fetchHotProducts = async () => {
  try {
    const response = await request.get('/products/hot');
    hotProducts.value = response.data;
  } catch (error) {
    console.error('获取热销产品失败:', error);
  }
};

const startCarousel = () => {
  carouselInterval.value = setInterval(() => {
    nextSlide();
  }, 5000);
};

onMounted(() => {
  fetchHotProducts();
  startCarousel();
});

onUnmounted(() => {
  if (carouselInterval.value) {
    clearInterval(carouselInterval.value);
  }
});
</script>

<style scoped>
.home {
  min-height: 100vh;
  background-color: var(--gray-50);
}

.main-layout {
  display: flex;
  gap: var(--spacing-8);
  padding: var(--spacing-8) 0;
}

.content-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: var(--spacing-8);
}

/* 轮播图样式 */
.carousel-container {
  position: relative;
  overflow: hidden;
  border: none;
  padding: 0;
}

.carousel {
  position: relative;
  height: 400px;
}

.slide {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  transition: opacity var(--transition-slow);
}

.slide.active {
  opacity: 1;
}

.slide img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.slide-content {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: var(--spacing-8);
  background: linear-gradient(to top, rgba(0, 0, 0, 0.8), transparent);
  color: var(--white);
}

.slide-title {
  font-size: var(--font-size-3xl);
  font-weight: var(--font-weight-bold);
  margin-bottom: var(--spacing-2);
  line-height: var(--line-height-tight);
}

.slide-description {
  font-size: var(--font-size-lg);
  opacity: 0.9;
  margin: 0;
}

.carousel-control {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background-color: rgba(0, 0, 0, 0.6);
  color: var(--white);
  border: none;
  width: 48px;
  height: 48px;
  border-radius: var(--radius-full);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all var(--transition-fast);
  z-index: 10;
}

.carousel-control:hover {
  background-color: rgba(0, 0, 0, 0.8);
  transform: translateY(-50%) scale(1.1);
}

.carousel-control svg {
  width: 20px;
  height: 20px;
  stroke: currentColor;
  fill: none;
}

.carousel-control.prev {
  left: var(--spacing-4);
}

.carousel-control.next {
  right: var(--spacing-4);
}

.carousel-indicators {
  position: absolute;
  bottom: var(--spacing-4);
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: var(--spacing-2);
  z-index: 10;
}

.carousel-indicators span {
  width: 12px;
  height: 12px;
  border-radius: var(--radius-full);
  background-color: rgba(255, 255, 255, 0.4);
  cursor: pointer;
  transition: all var(--transition-fast);
}

.carousel-indicators span:hover {
  background-color: rgba(255, 255, 255, 0.7);
}

.carousel-indicators span.active {
  background-color: var(--white);
  transform: scale(1.2);
}

/* 热销产品样式 */
.hot-products {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-6);
}

.section-header {
  text-align: center;
  margin-bottom: var(--spacing-6);
}

.section-title {
  font-size: var(--font-size-2xl);
  font-weight: var(--font-weight-bold);
  color: var(--gray-900);
  margin-bottom: var(--spacing-2);
}

.section-subtitle {
  font-size: var(--font-size-base);
  color: var(--gray-600);
  margin: 0;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: var(--spacing-6);
}

.product-card {
  cursor: pointer;
  border: none;
  padding: 0;
  overflow: hidden;
  transition: all var(--transition-normal);
}

.product-card:hover {
  transform: translateY(-4px);
  box-shadow: var(--shadow-lg);
}

.product-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform var(--transition-normal);
}

.product-card:hover .product-image img {
  transform: scale(1.05);
}

.hot-badge {
  position: absolute;
  top: var(--spacing-3);
  right: var(--spacing-3);
  font-size: var(--font-size-xs);
  font-weight: var(--font-weight-bold);
}

.product-info {
  padding: var(--spacing-4);
}

.product-name {
  font-size: var(--font-size-base);
  font-weight: var(--font-weight-medium);
  color: var(--gray-800);
  margin-bottom: var(--spacing-3);
  line-height: var(--line-height-tight);
  height: 48px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.price-section {
  display: flex;
  align-items: center;
  gap: var(--spacing-2);
}

.current-price {
  font-size: var(--font-size-lg);
  font-weight: var(--font-weight-bold);
  color: var(--error-color);
}

.original-price {
  font-size: var(--font-size-sm);
  color: var(--gray-500);
  text-decoration: line-through;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .main-layout {
    gap: var(--spacing-6);
  }
  
  .content-area {
    gap: var(--spacing-6);
  }
}

@media (max-width: 768px) {
  .main-layout {
    flex-direction: column;
    gap: var(--spacing-4);
  }
  
  .carousel {
    height: 300px;
  }
  
  .slide-title {
    font-size: var(--font-size-2xl);
  }
  
  .slide-description {
    font-size: var(--font-size-base);
  }
  
  .carousel-control {
    width: 40px;
    height: 40px;
  }
  
  .carousel-control.prev {
    left: var(--spacing-2);
  }
  
  .carousel-control.next {
    right: var(--spacing-2);
  }
  
  .product-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: var(--spacing-4);
  }
  
  .product-image {
    height: 160px;
  }
}

@media (max-width: 480px) {
  .product-grid {
    grid-template-columns: 1fr;
  }
  
  .carousel {
    height: 250px;
  }
  
  .slide-content {
    padding: var(--spacing-4);
  }
  
  .slide-title {
    font-size: var(--font-size-xl);
  }
  
  .slide-description {
    font-size: var(--font-size-sm);
  }
}
</style>